package net.hserver.admin.system.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.plugin.web.context.Webkit;
import cn.hserver.plugin.web.interfaces.GlobalException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.hserver.admin.system.common.MyCode;
import net.hserver.admin.system.common.MyException;
import net.hserver.admin.system.common.MyResult;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

@Bean
@Slf4j
public class ResponseException implements GlobalException {
    @Override
    public void handler(Throwable throwable, int i, String s, Webkit webkit) {

        if (throwable instanceof MyException) {
            log.error("「 ".concat(throwable.getMessage()).concat(" 」\n"), throwable);
            webkit.httpResponse.sendJson(((MyException) throwable).getResult());
            return;
        }
        if (throwable instanceof NotLoginException) {
            NotLoginException e = (NotLoginException) throwable;
            MyResult result = MyResult.failure();
            result.setCode(MyCode.NOT_LOGIN);
            String message;
            if (e.getType().equals(NotLoginException.NOT_TOKEN)) {
                message = "未能读取到有效 token";
            } else if (e.getType().equals(NotLoginException.INVALID_TOKEN)) {
                message = "token 无效";
            } else if (e.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
                message = "token 已过期";
            } else if (e.getType().equals(NotLoginException.BE_REPLACED)) {
                message = "token 已被顶下线";
            } else if (e.getType().equals(NotLoginException.KICK_OUT)) {
                message = "token 已被踢下线";
            } else {
                message = "当前会话未登录";
            }
            result.setMessage(message);
            log.error("「 ".concat(message).concat(" 」\n"), e);
            webkit.httpResponse.sendJson(result);
            return;
        }

        MyResult result = MyResult.failure();
        if (throwable instanceof DuplicateKeyException) {
            result.setCode(MyCode.DUPLICATE_KEY);
        } else if (throwable instanceof NullPointerException) {
            result.setCode(MyCode.NPE);
        } else if (throwable instanceof NotPermissionException || throwable instanceof NotRoleException) {
            result.setCode(MyCode.ACCESS_DENIED);
        } else {
            result.setCode(MyCode.SERVER_ERROR);
        }
        log.error("「 ".concat(result.getMessage()).concat(" 」\n"), throwable);
        webkit.httpResponse.sendJson(result.setException(throwable.getLocalizedMessage()));
    }
}
